import React, {PropsWithChildren, useEffect, useState} from 'react'
import {Checkbox, CheckboxGroup, Dialog, } from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";

export interface ExportToExcelConfigurationDialogProps extends PropsWithChildren {
    selectableColumns: { key:string,header:string }[]
    rememberedColumnsStorageKey:string
    onConfirm:(selectedColumns:string[])=>Promise<void>
    visible:boolean
    onCancel:()=>void
}


const ExportToExcelConfigurationDialog: React.FC<ExportToExcelConfigurationDialogProps> = (props) => {
    const [selectedColumns,setSelectedColumns] = useState<string[]>([])
    const [remembered,setRemembered] = useState(false)
    useEffect(() => {
        const rememberedColumns = (Taro.getStorageSync(props.rememberedColumnsStorageKey) as string[])||[]
        if (rememberedColumns.length){
            setSelectedColumns(props.selectableColumns.map(it=>it.key).filter(it=>rememberedColumns.includes(it)))
        }else {
            setSelectedColumns(props.selectableColumns.map(it=>it.key))
        }
    }, [props.selectableColumns]);

    return <>
        <Dialog {...props} onConfirm={async ()=>{
            await props.onConfirm(selectedColumns)
            if (remembered) {
                Taro.setStorageSync(props.rememberedColumnsStorageKey, selectedColumns)
            }
        }}>
            <CheckboxGroup direction={"horizontal"} value={selectedColumns} onChange={value => {
                setSelectedColumns(value)
            }}>
                {props.selectableColumns.map(column=>{
                    return <Checkbox value={column.key}>{column.header}</Checkbox>
                })}
            </CheckboxGroup>
            <Checkbox style={{marginTop:16}} label={"记住本次选择"} checked={remembered} onChange={setRemembered}/>
        </Dialog>
    </>
}

export default ExportToExcelConfigurationDialog